<template>
  <div class="app-container">
    <el-row>
      <el-col :span="18">
        <div style="padding: 16px 0; margin: 0 16px 16px 0;">
           <div style="display: flex;">
            <el-avatar shape="square" :size="50" :style="style">{{ info.ComInitial }}</el-avatar>
            <div style="margin-left: 15px;">
              <div style="margin-bottom: 16px;">
                <span style="margin-right: 20px;color: #404040;font-size: 20px;font-weight: 600"> {{ info.ComName }}
                  <el-button v-if="lockOpen" size="mini" type="danger" icon="el-icon-circle-plus-outline"
                    style="margin-left: 10px;" @click="addCus()">添加至系统客户</el-button></span>
              </div>
              <div v-if="info.ComStatus" style="margin-bottom: 13px">
                <el-tag size="mini" type="warning">{{ info.ComStatus }}</el-tag>
              </div>
            </div>
           </div>
          <el-row>
            <el-col>
                <el-descriptions class="simple-auto-column" :column="3">
                  <el-descriptions-item v-for="(item, index) in descList" :key="index" :label="item"
                    :content-style="index === 'ComLegalPerson' ? { 'color': '#0087FE'} : {padding: '0 10px 0 0',}"
                    :label-style="{whiteSpace: 'nowrap',color: '#CFCFCF'}"
                    >
                    {{ info[index] }}
                  </el-descriptions-item>
                </el-descriptions>
            </el-col>
          </el-row>
        </div>
        <div style="background-color: #fff;margin: 0 16px 16px 0; border-radius:  10px;">
          <sub-nav-tabs :tabs-list="tabsList" :active-name="activeName" :company-id="companyId" :info="info" />
        </div>
      </el-col>
      <el-col :span="6">
        <el-tabs v-model="conContentType" type="border-card" @tab-click="handleClickContacts">
          <el-tab-pane v-for="(contactsItem,contactsIndex) in tabsListContacts" :name="contactsItem.name" :disabled="!lockOpen">
            <span slot="label"> {{ contactsItem.label }}
              <el-badge :value="comCount[contactsItem.value]" class="item"></el-badge>
            </span>
            <!-- 有解锁 -->
            <div v-if="lockOpen">
              <div v-for="(item, index) in Contacts" :key="index" class="infinite-list-item">
                <div class="card-content">
                  <p v-show="item.ConName"><i class="el-icon-user" style="margin-right: 5px;" />联系人：{{ item.ConName
                    }}</p>
                  <div style="display: flex;">
                    <div><i class="el-icon-phone-outline" style="margin-right: 5px;" />联系方式：</div>
                  
                  <div v-if="contactsIndex===0" :ref="`phone-${item.Id}`"> {{ item.ConContent }}
                      <i class="el-icon-view" style="color: #0087FE; cursor: pointer;" @click="openphone(item)"></i>
                    </div>
                    <div v-else> {{ item.ConContent }}</div>
                </div>
                  <p v-show="item.ConTitle"><i class="el-icon-user-solid" style="margin-right: 5px;" />职务：{{
                    item.ConTitle }}</p>
                  <p v-show="item.ConUpdateOn"><i class="el-icon-alarm-clock" style="margin-right: 5px;" />更新时间：{{
                    item.ConUpdateOn }}</p>
                </div>
                <div class="card-foot">
                  <div
                    style="display: flex;justify-content: left;align-items: center;white-space: nowrap; margin-right: 6px;">
                    <el-image style="width: 17px; height: 15px; margin-right: 4px;"
                      :src="require('@/assets/icon1.png')" fit="fill" />
                    <span>来自</span>
                  </div>
                  <el-tooltip placement="top" effect="light">
                    <div slot="content">
                      <div v-for="(item2) in item.Source" style="margin: 5px 0;color: #409EFF;">{{ item2 }}</div>
                      <br />
                    </div>
                    <el-button type="text" class="single-line">
                      {{ item.Source[0] }}
                    </el-button>
                  </el-tooltip>
                </div>
              </div>
              <div style="color: #CFCFCF; font-size: 13px; margin: 30px; text-align: center;">——没有更多联系方式了——</div>
            </div>
            <!-- 没解锁 -->
            <div v-else>
              <el-empty :description="comCount.ContactCount + '个联系方式'">
                <div v-if="info.ComLockStatus === 1">
                  <el-button  :type="'danger'" @click="openLock()" :disabled="comCount.ContactCount === 0 ? true:false"><i class="el-icon-lock"
                    style="margin-right: 2px;"></i>当前企业解锁次数已达上限</el-button>
                    <div style="border: 1px solid #dcdfe6; margin-top: 20px;">
                      <el-divider content-position="left">温馨提示：</el-divider>
                      <div style="font-size: 14px;text-indent: 2rem;padding: 0 20px 20px 20px; text-align: left;color: #67C23A;line-height: 20px;"> 企业被三个账号解锁后被视为解锁次数已达上线，将被锁定一个月，将在一个月后才可进行解锁。</div>
                    </div>
                </div>
                <el-button v-else :type="'primary'" @click="openLock()" :disabled="comCount.ContactCount === 0 ? true:false"><i class="el-icon-lock"
                    style="margin-right: 2px;"></i>解锁企业并查看</el-button>
              </el-empty>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <el-dialog :title="'选择需要入库的联系人'" :visible.sync="addUserDialog">
      <el-form ref="dataFormAddUser" :rules="rulesAddUser" :model="tempAddUser" label-position="left"
        label-width="120px" style="margin-left:50px;margin-right:50px;">
        <el-table 
            ref="multipleTable"
            height="500"
            :data="openphoneList.filter(data => !search || data.ConContent.toLowerCase().includes(search.toLowerCase()))"
            tooltip-effect="dark" 
            style="width: 100%" 
            empty-text="暂无查看联系方式"
            @selection-change="handleSelectionChange">
            
          <el-table-column type="selection" width="55">
          </el-table-column>

          <el-table-column v-for="(item, index) in tableTitle" :key="index" :prop="item.value" :label="item.label">
            <template v-slot="scope">
              <template v-if="item.type === 'text'">
              <!-- <div v-if="item.phone">111{{ maskPhone(scope.row[item.value]) }}</div> -->
              <div>{{ scope.row[item.value] }}</div>
            </template>
            </template>
          </el-table-column>

          <el-table-column align="right">
            <template slot="header" slot-scope="scope">
              <el-input v-model="search" size="mini" clearable placeholder="输入联系方式" />
            </template>
          </el-table-column>

        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserDialog = false">
          取消
        </el-button>
        <el-button type="primary" @click="getNumber()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import SubNavTabs from '@/views/retrievalNumber/info/components/subNavTabs.vue'
import { getComDetail, getComContacts, getComContactCount, ComContactUnlock, AddCustomerRecords,GetContactInfo } from '@/api/company'
import { extractColorByName } from '@/utils'
import { TipsBox } from '@/utils/feedback'
import BasicTable from '@/components/BasicTable/index.vue'
import Cookies from 'js-cookie'
export default {
  name: 'RetrievalInfo',
  components: { BasicTable, SubNavTabs },
  data() {
    return {
      tabsListContacts: [
        { name: '1', label: '手机', value: 'MobileCount' },
        { name: '2', label: '固话', value: 'LandlineCount' },
        { name: '3', label: '邮箱', value: 'EmailCount' },
        { name: '4', label: 'QQ', value: 'QQCount' }
      ],
      lockOpen: false,
      activeName: 'Qualifications', //BasicInfos
      tabsList: [],
      info: {},
      companyId: '',
      Contacts: [],
      conContentType: '1',
      style: {
        backgroundColor: '',
        fontSize: '2.2rem'
      },
      load: false,
      descList: {
        ComLegalPerson: '企业法人',
        ComType: '企业登记注册类型',
        ComNumber: '统一社会信用代码',
        ComScale: '公司规模',
        ComStartDate: '成立日期',
        ComRegisterOffice: '登记机关',
        ComCapital: '注册资本',
        ComIndustry: '所属行业',
        ComDistFullName: '企业注册地',
        ComAddress: '企业地址',
        ComFormerName: '曾用名',
        ComSocialInsuranceCount: '参保人数',
        ComTradeScope: '经营范围' 
      },
      comCount: null,
      addUserDialog: false,
      rulesAddUser: {},
      tempAddUser: {},
      tableTitle: [
        {
          label: '联系人',
          value: 'ConName',
          show: true,
          type: 'text'
        },
        {
          label: '联系方式',
          value: 'ConContent',
          show: true,
          type: 'text',
          phone: true
        },
      ],
      multipleSelection: [],
      search: '',
      tabIndex: null,
      rolepanduan:null,
      pagerole:null,
      openphoneList:[]
    }
  },
  created() {
    this.companyId = this.$route.query.id
    if (!this.companyId) {
      this.$router.replace({
        path: '/retrievalNumber'
      })
    }
    this.getInfo()
    this.getComContactCounts()
    this.getContacts(this.conContentType)
    // 要求tabs根据角色显示隐藏
    this.pagerole = Cookies.get('role')
    if(this.pagerole.search('4')!=-1 || this.pagerole.search('0')!=-1 ){
      this.tabsList.push(
        // { component: 'BasicInfos', name: '企业信息',show:true },
        { component: 'Qualifications', name: '企业资质',show:true },
        { component: 'Project', name: '工程项目',show:true },
        { component: 'Concat', name: '注册人员',show:true },
       { component: 'Engineer', name: '职称人员',show: true })
    }else{
      this.tabsList.push(
        // { component: 'BasicInfos', name: '企业信息',show:true },
        { component: 'Qualifications', name: '企业资质',show:true },
        { component: 'Project', name: '工程项目',show:true },
        { component: 'Concat', name: '注册人员',show:true },
        { component: 'Engineer', name: '职称人员',show: false })
    }
  },
  methods: {
    openphone(v){
      const params ={
        contactId: v.Id
      }
      GetContactInfo(params).then((res)=>{
        this.$nextTick(function(){
          const refName = `phone-${v.Id}`;
          const element = this.$refs[refName][0];
          element.textContent = res.data.ConContent
          v.ConContent = res.data.ConContent
          this.openphoneList.push(v)
        })
      })
    },
    maskPhone(phone) {
      if (!phone || phone.length !== 11) return phone; 
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1***$2');
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getNumber() {
      const a = []
      const a2 = []
      if (this.multipleSelection.length === 0) {
        TipsBox('error', '请选择一条数据添加');
        return;
      }
      this.multipleSelection.forEach((item) => {
        a.push({ ConName: item.ConName, ConContent: item.ConContent })
        a2.push(item.Id)
      }
      )
      const params = {
        ComName: this.info.ComName,
        data: a,
      }
      // 要求：调用crm的方法，把值params送过去。如果成功再调用这边后台方法。
      var b = BildingPlatform.createCustomerInfoDemo(params); // 这个是crm那边的方法
      if (b === 0) {
        TipsBox('error', '添加失败')
        this.addUserDialog = false
      } else if (b === 1){
        TipsBox('success', '添加客户成功')
        // 调用后台方法
        AddCustomerRecords({IdList:a2}).then((res)=>{
          this.addUserDialog = false
          TipsBox('success', '添加记录成功')
        })
      }else if (b === 2){
        TipsBox('warning', '取消添加操作')
        this.addUserDialog = false
      }
    },
    addCus() {
      if (this.tabIndex === '1') {
        this.addUserDialog = true
        // this.tableData = this.Contacts
      }
    },
    handleClickContacts(tab) {
      this.getContacts(tab.name)
    },
    getInfo() {
      this.loading = true
      getComDetail({ companyId: this.companyId }).then((res) => {
        this.loading = false
        if (res.code === 200) {
          this.info = res.data.CompanyDetail
          this.tabsList[0].name += '(' + res.data.CompanyDetail.ZiZhiCount + ')'
          this.tabsList[1].name += '(' + res.data.CompanyDetail.ProjectCount + ')'
          this.tabsList[2].name += '(' + res.data.CompanyDetail.RegPersonCount + ')'
          this.tabsList[3].name += '(' + res.data.CompanyDetail.ProfePersonCount + ')'

          this.style.backgroundColor = extractColorByName(this.info.ComName)
        }
      })
    },
    // 数量
    getComContactCounts() {
      this.loading = true
      getComContactCount({ companyId: this.companyId }).then((res) => {
        this.loading = false
        if (res.code === 200) {
          this.comCount = res.data
        }
      })
    },
    // 请求是否解锁
    getContacts(conContentTypeParams) {
      this.tabIndex = conContentTypeParams
      this.loading = true
      getComContacts({ companyId: this.companyId, conContentType: conContentTypeParams }).then((res) => {
        this.loading = false
        if (res.code === 200) {
          this.Contacts = res.data.pageList
          this.lockOpen = res.Unlock
        }
      })
    },
    // 开锁
    openLock() {
      this.loading = true
      if(this.info.ComLockStatus === 1){
        return
      }
      ComContactUnlock({ companyId: this.companyId }).then((res) => {
        this.loading = false
        if (res.code === 200) {
          this.lockOpen = true
          // 点击一下tab
          this.handleClickContacts({ name: '1' })
          this.getContacts(this.conContentType)
        }
      })
    },
  }
}
</script>
<style lang="scss" scoped>

::v-deep .simple-auto-column .el-descriptions__body{
  background-color: rgb(245, 250, 255) !important;
  padding: 15px;
}
.card-box {
  background-color: #fff;
  padding: 16px;
  border-radius: 5px;
  overflow: auto;
}

.infinite-list {
  height: 760px;
  padding: 0;
  margin: 0;
  list-style: none;
}

.infinite-list-item {
  border: 1px solid #E8E8E8;
  margin-bottom: 16px;
  padding: 16px;
  border-radius: 5px;
}

.infinite-list-item:hover {
  border-color: #ddd;
  background-color: rgba(250, 251, 253, .3);
  box-shadow: 3px 3px 5px #E8E8E8;

  .card-content {
    border-bottom-color: #ddd;
  }
}

.card-title {
  font-size: 20px;
  color: #404040;
  margin-bottom: 10px;
  font-weight: 600
}

.card-content {
  font-size: 13px;
  color: #6d6d6d;
  margin-bottom: 16px;
  border-bottom: 1px solid #E8E8E8;
}

.card-foot {
  color: #6D6D6D;
  font-size: 10px;
  display: flex;
  align-items: center;
}

.single-line {
  white-space: nowrap;
  /* 保证文本单行显示 */
  overflow: hidden;
  /* 超出容器部分隐藏 */
  text-overflow: ellipsis;
  /* 超出部分显示为省略号 */
  max-width: 100%;
  /* 最大宽度为容器宽度 */
}
</style>
